package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sintang
 * @date 2020-09-03 22
 */
public class SimpleExecutor implements Executor {
    /**
     * 查询方法
     *
     * @param configuration
     * @param mappedStatement
     * @param params
     * @return
     */
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1、注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        // 2、获取sql
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3、获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4、获取到参数的对象
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = paramTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 获取结果类型
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        // 封装结果结果集
        ArrayList<Object> objects = new ArrayList<>();
        while(resultSet.next()){
            Object o =resultTypeClass.newInstance();
            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i =1;i<=metaData.getColumnCount();i++){
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);

        }


        return (List<E>) objects;
    }

    /**
     * 增删改对应的方法
     *
     * @param configuration
     * @param mappedStatement
     * @param params
     * @throws Exception
     */
    @Override
    public void insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        System.out.println("我是insert的方法");
        // 1、注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        // 2、获取sql
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3、获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4、获取到参数的对象
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = paramTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }

        // 执行sql
         preparedStatement.executeUpdate();
    }

    @Override
    public void update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 因为insert、update、delete执行方法是一样的，所以这里统一用insert的方法
        System.out.println("我是update方法");
        insert(configuration, mappedStatement, params);
    }

    @Override
    public void delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 因为insert、update、delete执行方法是一样的，所以这里统一用insert的方法
        System.out.println("我是delete方法");
        insert(configuration, mappedStatement, params);
    }

    /**
     * 解析sql
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql){
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }

    /**
     * 根据类的全路径获取到对应的class文件
     * @param classPath
     * @return
     */
    private Class<?> getClassType(String classPath) throws ClassNotFoundException {
        if(classPath != null ){
            Class<?> aClass = Class.forName(classPath);
            return aClass;
        }
        return null;
    }
}
